package com.ximu.test.base.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Server2 {
	
	private static ServerSocket server = null;
	private static List<Socket> socketList = new ArrayList<Socket>();
	public static void main(String[] args){
		
		class SocketThread extends Thread{
			private Socket socket;
			private Integer id;
			public SocketThread(Socket socket,Integer id) {
				this.socket = socket;
				this.id = id;
			}
			
			public void run(){
				System.out.println("有客户端连接:id="+id);
				System.out.println("开始监听客户端:id="+id);
				try {
					BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					PrintWriter socketWriter = new PrintWriter(socket.getOutputStream());
					socketWriter.println("客户端id为:"+id);
					socketWriter.flush();
					String clientInput = socketReader.readLine();
					while( clientInput!=null && !clientInput.equals("quit")){
						System.out.println("客户端"+id+":"+clientInput);
						socketWriter.println("服务端收到"+clientInput);
						socketWriter.flush();
						//根据客户端数据向其他客户端做转发
						Matcher matcher = Pattern.compile("(\\d+?):.*").matcher(clientInput);
						while(matcher.find()){
							System.out.println("向客户端<"+matcher.group(1)+">转发数据");
							Socket otherSocket = socketList.get(Integer.parseInt(matcher.group(1))-1);
							if(otherSocket!=null){
								PrintWriter otherSocketPrint = new PrintWriter(otherSocket.getOutputStream());
								otherSocketPrint.println("来自客户端<"+id+">:"+clientInput);
								otherSocketPrint.flush();
							}else{
								System.out.println("客户端<"+matcher.group(1)+">不存在");
							}
						}
						clientInput = socketReader.readLine();
					}
					socketReader.close();
					socketWriter.close();
					socket.close();
					System.out.println("客户端"+id+"监听线程退出");
				} catch (IOException e) {
					e.printStackTrace();
				}				
			}
		}
		Socket socket;
		SocketThread socketThread;
		try{
			server = new ServerSocket(2012);
			System.out.println("开始监听客户端:");
			Integer id = 1;
			while(true){
				socket = server.accept();
				socketList.add(socket);//加入socket连接池
				socketThread = new SocketThread(socket,id);
				socketThread.start();
				id++;
			}
		}catch(IOException e){
			System.out.println("创建服务失败");
		}
		System.out.println("exit");
	}
}
